package ma.meditel.reporting.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import ma.meditel.reporting.entities.Interface;
import ma.meditel.reporting.entities.Traffic;
import ma.meditel.reporting.entities.TrafficNotification;
import ma.meditel.reporting.metier.interfaces.IInterfaceMetier;
import ma.meditel.reporting.metier.interfaces.ITrafficMetier;
import ma.meditel.reporting.metier.interfaces.ITrafficNotificationMetier;
import ma.meditel.reporting.util.ChartJSONObject;
import ma.meditel.reporting.util.JSONColor;
import ma.meditel.reporting.util.TrafficsHelper;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

public class TrafficsInOutGrapheAction extends ActionSupport {
	private static final long serialVersionUID = -7313259148450753790L;
	
	private static final String MESSAGE_ERROR_INPUT = "Veuillez remplir tous les champs.";
	private static final String MESSAGE_INTERFACES_EMPTY = "Veuillez choisir une interface.";
	private static final String MESSAGE_TYPE_TRAFFIC_EMPTY = "Veuillez selectioner un type de traffic.";
	private static final String MESSAGE_ERROR_DATE_1 = "Date de début doit être inférieur ou égal au Date de fin.";
	private static final String MESSAGE_ERROR_DATE_2 = "Veuillez respecter le format du date (yyyy-MM-dd hh:mm).";
	private static final String MESSAGE_ERROR_DATE_3 = "Veuillez vérifier si la date entrée en paramètre est inférieur à aujourd'hui.";
	private static final String MESSAGE_ERROR_INTERFACE_OVER_SIZE = "Echec de la représentation: Nombre d'interface superieur à 6.";
	private static final String MESSAGE_ERROR_DATA_OVER_SIZE = "Echec de la représentation: Vieullez choisir une autre valeur de marge (Graphe trop chargé ou trop faible).";
	private static final String MESSAGE_NO_DATA = "Echec de la représentation: Données insuffisantes pour la représentation.";
	
	@Autowired
	public IInterfaceMetier interfaceMetier;
	@Autowired
	public ITrafficMetier trafficMetier;
	@Autowired
	public ITrafficNotificationMetier trafficNotificationMetier;
	
	public Long[] interfacesId;
	public String startDate, endDate;
	public String[] typeTraffic;
	public String grapheType;
	public String grapheNotificationType;
	public String grapheNotificationVu;
//	public int margeAgregation = 15;
	public int margeAgregation;
	public String niveauAgregation = "avg";
	public TrafficNotification trafficNoti;
	public String chartData;//Chart Json String
	
	private Date sdate, edate;
	
	@SuppressWarnings("deprecation")
	@Override
	public String execute() {
		//Apres validation
		if(interfacesId != null && typeTraffic != null && startDate!=null && endDate!=null && grapheType!=null){
			
			//new JSON Object
			ChartJSONObject jsonObj = new ChartJSONObject(); 
			jsonObj.renderLabel(sdate, edate, margeAgregation);
			
			//Verfier si le graphe support l'information
			if(!jsonObj.isDatasetRepresentable()){
				addActionError(MESSAGE_ERROR_DATA_OVER_SIZE);
				return ActionSupport.INPUT;
			}
			
			//Fill dataSets with traffics from DB
			for(int i = 0; i<interfacesId.length; i++) { //for each interface selected
				
				for(int j = 0; j<typeTraffic.length; j++) { //for each type selected (in,out)
					//get All traffics for interfacesId[i] between sdate and edate
					List<Traffic> traffics = trafficMetier.getAllInterfaceTrafficsBetween(interfacesId[i], sdate, edate, typeTraffic[j]);
					
					if(traffics.size() <= 0){
						break;
					}
					
					List<Double> finalDataset = null;
					
					
						if(niveauAgregation.compareTo("avg") == 0) finalDataset = TrafficsHelper.newTrafficsToAVG_(traffics,margeAgregation,sdate);
						else
						{
							if(niveauAgregation.compareTo("min") == 0) finalDataset = TrafficsHelper.newTrafficsToMin_(traffics,margeAgregation, sdate);
							else
							{
								finalDataset = TrafficsHelper.newTrafficsToMax_(traffics,margeAgregation, sdate);
							}
						}
						
					
					
//					for(Double d : finalDataset)
//					{
//						System.out.println("finalDataset -> value : "+d);
//					}
					
					//Set JsonObject attributes
					jsonObj.addDataset();
					jsonObj.getLastDataset().setData(finalDataset);
					
					System.out.println("size: " + finalDataset.size());
					//end set Attributes
					
					//Format Graphe (Title and Label and Color)
					try {
						Interface _interface = interfaceMetier.getInterface(interfacesId[i]);
						jsonObj.getLastDataset().setLabel(_interface.getIfAlias() + " (" + typeTraffic[j] + ")");
						jsonObj.getLastDataset().setTitle(_interface.getIfAlias() + " (" + typeTraffic[j] + ")");
						jsonObj.getLastDataset().setColor(JSONColor.getLisColors(j)[i]);
						
						//affichage for me 
						
//						System.out.println(" interface name : " + _interface.getIfName()
//											+ " type : " + _interface.getIfType() 
//											+ " alias : " + _interface.getIfAlias());
//						System.out.println();
					
						
						//end message for me
						
					} catch (Exception e) {}
					
					
					
				}//End TypeTraffic boucle
				
			}//End interfacesId boucle
			
			//Convert JsonObject to String
			if(jsonObj.getDatasets().size() <= 0){
				addActionError(MESSAGE_NO_DATA);
			}
			chartData = new Gson().toJson(jsonObj);
		}
		
		if(grapheNotificationType != null && grapheNotificationType != "")
		{
			trafficNoti = new TrafficNotification();
			trafficNoti.setDateJour(sdate);
			try {
				trafficNoti.setIinterface(interfaceMetier.getInterface(interfacesId[0]));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			trafficNoti.setNotificationVu(0);
			trafficNoti.setTypeOrClassTraffic(typeTraffic[0]);
			
			
			if(grapheNotificationVu == null || grapheNotificationVu == "")
			{
				TrafficNotification theNotiForMerge = trafficNotificationMetier.getTrafficNotificationWithoutId(
				trafficNoti.getIdInterface(), trafficNoti.getDateJour(), trafficNoti.getTypeOrClassTraffic());
				
				if(!theNotiForMerge.testNotificationVu())
				{
					theNotiForMerge.setNotificationVu(1);
					trafficNotificationMetier.mergeTrafficNoti(theNotiForMerge);
				}
			}
			
			
			return "GrapheNotification";
		}else {
			return ActionSupport.SUCCESS;
		}
		
		
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void validate() {
		
		
		if(interfacesId==null){
			addActionError(MESSAGE_INTERFACES_EMPTY);
			return;
		}
		if(startDate==null || endDate==null || grapheType==null){
			addActionError(MESSAGE_ERROR_INPUT);
			return;
		}
		
		if(typeTraffic==null){
			addActionError(MESSAGE_TYPE_TRAFFIC_EMPTY);
			return;
		}
		if(interfacesId.length > 6){
			addActionError(MESSAGE_ERROR_INTERFACE_OVER_SIZE);
			return;
		}
		
//		startDate = "2014-08-10 20:10:00";
//		endDate = "2014-08-18 20:10:00";
		
		
		//validation date
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			sdate = formatter.parse(startDate+":00");
			edate = formatter.parse(endDate+":00");
			System.out.println(sdate.getMonth());
			//define date interval (forcage des minutes)
			int sMinutes = (sdate.getMinutes()/5) * 5;
			int eMinutes = (edate.getMinutes()/5) * 5 + 5;
			
			sdate.setMinutes(sMinutes);
			edate.setMinutes(eMinutes);
			
			//Date should be < new date (now)
			if(edate.compareTo(new Date()) > 0){
				addActionError(MESSAGE_ERROR_DATE_3);
				return;
			}
			//sDate sould be < eDate
			if(sdate.compareTo(edate)  > 0){
				addActionError(MESSAGE_ERROR_DATE_1);
				return;
			}
			
			
			
		} catch (ParseException e) {
			addActionError(MESSAGE_ERROR_DATE_2);
			return;
		}//end dateFormat try
		
	}

}
